package com.example.a13001.shoppingmalltemplate.activitys;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.a13001.shoppingmalltemplate.R;
import com.example.a13001.shoppingmalltemplate.base.AppConstants;
import com.example.a13001.shoppingmalltemplate.base.BaseActivity;
import com.example.a13001.shoppingmalltemplate.manager.DataManager;
import com.example.a13001.shoppingmalltemplate.modle.Address;
import com.example.a13001.shoppingmalltemplate.modle.CommonResult;
import com.example.a13001.shoppingmalltemplate.utils.MyUtils;
import com.example.a13001.shoppingmalltemplate.utils.Utils;
import com.smarttop.library.bean.City;
import com.smarttop.library.bean.County;
import com.smarttop.library.bean.Province;
import com.smarttop.library.bean.Street;
import com.smarttop.library.db.manager.AddressDictManager;
import com.smarttop.library.widget.AddressSelector;
import com.smarttop.library.widget.BottomDialog;
import com.smarttop.library.widget.OnAddressSelectedListener;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

public class NewAddressActivity extends BaseActivity implements OnAddressSelectedListener, AddressSelector.OnDialogCloseListener {
    @BindView(R.id.iv_title_back)
    ImageView ivTitleback;
    @BindView(R.id.tv_title_center)
    TextView title;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.tv_diqu)
    TextView tvDiqu;
    @BindView(R.id.ll_address)
    LinearLayout llAddress;
    @BindView(R.id.et_addressdetail)
    EditText etAddressdetail;
    @BindView(R.id.btn_save)
    Button btnSave;
    @BindView(R.id.rl)
    RelativeLayout rl;
    @BindView(R.id.et_postalcode)
    EditText etPostalcode;
    @BindView(R.id.cb_default)
    CheckBox cbDefault;
    //地址选择相关
    private PopupWindow popWnd;
    private BottomDialog dialog;
    private AddressDictManager addressDictManager;
    private String provinceCode;
    private String cityCode;
    private String countyCode;
    private String streetCode;
    private DataManager manager;
    private CompositeSubscription mCompositeSubscription;
    private int addressId = 0;
    private String mProvince;
    private String mProvince1;
    private String mCity;
    private String mCity1;
    private String mArea;
    private String mArea1;
    private int addressDefault = 0;
    private CommonResult mCommonResult;
    private Address mAddress;
    private static final String TAG = "NewAddressActivity";
    private String safetyCode;
    private String timeStamp;
    private String code;
    private int pageindex = 1;
    private int main = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        setContentView(R.layout.activity_new_address);
        ButterKnife.bind(this);
        if (getIntent() != null) {
            addressId = getIntent().getIntExtra("addressid", 0);
            Log.e(TAG, "onCreate: " + addressId);
        }
        mCompositeSubscription = new CompositeSubscription();
        manager = new DataManager(NewAddressActivity.this);
        title.setText("收货地址管理");
        AddressSelector selector = new AddressSelector(this);
        //获取地址管理数据库
        addressDictManager = selector.getAddressDictManager();
        if (addressId > 0) {
            safetyCode = MyUtils.getMetaValue(NewAddressActivity.this, "safetyCode");
            code = Utils.md5(safetyCode + Utils.getTimeStamp());
            timeStamp = Utils.getTimeStamp();
            getAdressList(AppConstants.COMPANY_ID, code, timeStamp, AppConstants.PAGE_SIZE, pageindex, main, String.valueOf(addressId));
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }


    public void onAddressSelected(Province province, City city, County county, Street street) {
        provinceCode = (province == null ? "" : province.code);
        cityCode = (city == null ? "" : city.code);
        countyCode = (county == null ? "" : county.code);
        streetCode = (street == null ? "" : street.code);
        String s = (province == null ? "" : province.name) + (city == null ? "" : city.name) + (county == null ? "" : county.name) +
                (street == null ? "" : street.name);
        mProvince = province == null ? "" : province.name;
        mProvince1=mProvince+"|"+provinceCode;
        mCity = city == null ? "" : city.name;
        mCity1=mCity+"|"+cityCode;
        mArea = county == null ? "" : county.name;
        mArea1=mArea+"|"+countyCode;
        tvDiqu.setText(s);
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    @Override
    public void dialogclose() {
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    @OnClick({R.id.iv_title_back, R.id.btn_save, R.id.ll_address})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_title_back:
                onBackPressed();
                break;
            /**
             * 保存
             */
            case R.id.btn_save:
                String name = etName.getText().toString().trim();
                String phone = etPhone.getText().toString().trim();
                String detailAddress = etAddressdetail.getText().toString().trim();
                String postalCode = etPostalcode.getText().toString().trim();
                if (TextUtils.isEmpty(name)) {
                    Toast.makeText(this, "请输入收货人姓名", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(phone)) {
                    Toast.makeText(this, "请输入收货人手机", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(phone)) {
                    Toast.makeText(this, "请输入收货人手机", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(detailAddress)) {
                    Toast.makeText(this, "请输入详细地址", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(postalCode)) {
                    Toast.makeText(this, "请输入邮政编码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (postalCode.length()!=6){
                    Toast.makeText(this, "邮政编码必须为6位", Toast.LENGTH_SHORT).show();
                    return;
                }
                String safetyCode = MyUtils.getMetaValue(NewAddressActivity.this, "safetyCode");
                String code = Utils.md5(safetyCode + Utils.getTimeStamp());
                Log.e(TAG, "onViewClicked: " + addressId);
                if (cbDefault.isChecked()){
                    addressDefault=1;
                }else{
                    addressDefault=0;
                }
                Log.e(TAG, "onViewClicked: "+mProvince1+"==mProvince=="+mProvince+"==mCity1=="+mCity1+"mCity"+mCity);
                editAddress(AppConstants.COMPANY_ID, code, Utils.getTimeStamp(), addressId, name, phone, mProvince, mCity, mArea, detailAddress, postalCode, addressDefault);

                break;
            //地址
            case R.id.ll_address:
                if (dialog != null) {
                    dialog.show();
                } else {
                    dialog = new BottomDialog(this);
                    dialog.setOnAddressSelectedListener(this);
                    dialog.setDialogDismisListener(this);
                    dialog.setTextSize(14);//设置字体的大小

                    dialog.setIndicatorBackgroundColor(R.color.ff2828);//设置指示器的颜色
                    dialog.setTextSelectedColor(R.color.ff2828);//设置字体获得焦点的颜色
                    dialog.setTextUnSelectedColor(R.color.t333);//设置字体没有获得焦点的颜色
                    dialog.show();
                }


                break;
        }
    }

    private void showPopUpWindow() {
        View contentView = LayoutInflater.from(NewAddressActivity.this).inflate(R.layout.pop_address_picker, null);
        popWnd = new PopupWindow(NewAddressActivity.this);
        popWnd.setContentView(contentView);
//    popWnd.setWidth(263);
//    popWnd.setHeight(320);
        popWnd.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popWnd.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
//        AddressSelector addressSelector = (AddressSelector) contentView.findViewById(R.id.apvAddress);

//        addressView.setOnAddressPickerSure(new AddressPickerView.OnAddressPickerSureListener() {
//            @Override
//            public void onSureClick(String address, String provinceCode, String cityCode, String districtCode) {
//                tvDiqu.setText(address);
//                popWnd.dismiss();
//            }
//        });

        popWnd.setTouchable(true);
        popWnd.setFocusable(true);
        popWnd.setOutsideTouchable(true);
        popWnd.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
//        backgroundAlpha(0.6f);

        //添加pop窗口关闭事件
//        popWnd.setOnDismissListener(new poponDismissListener());

        popWnd.setTouchInterceptor(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    popWnd.dismiss();
                    return true;
                }
                return false;
            }
        });

        //popWnd.showAsDropDown(mTvLine, 200, 0);
        popWnd.showAtLocation(NewAddressActivity.this.findViewById(R.id.ll_address),
                Gravity.BOTTOM, 0, 0);

    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    /**
     * 编辑收货地址
     *
     * @param companyid       站点ID
     * @param code            安全校验码
     * @param timestamp       时间戳
     * @param addressid       收货地址ID，为0时是添加新地址，大于0是修改指定ID收货地址
     * @param addressName     收货人名字
     * @param addressPhone    收货人手机
     * @param addressProvince 收货人所在省/市
     * @param addressCity     收货人所在市/区
     * @param addressArea     收货人所在区/县
     * @param addressXX       收货人详细地址
     * @param addressZipcode  收货人邮编
     * @param addressDefault  默认收货地址 0 否 1 是
     * @return
     */
    public void editAddress(String companyid, String code, String timestamp, int addressid, String addressName, String addressPhone, String addressProvince, String addressCity, String addressArea, String addressXX, String addressZipcode, int addressDefault) {

        mCompositeSubscription.add(manager.editAddress(companyid, code, timestamp, addressid, addressName, addressPhone, addressProvince, addressCity, addressArea, addressXX, addressZipcode, addressDefault)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CommonResult>() {
                    @Override
                    public void onCompleted() {
                        Log.e(TAG, "onCompleted: " + mCommonResult.toString());
                        int status = mCommonResult.getStatus();
                        if (status > 0) {
                            Toast.makeText(NewAddressActivity.this, "" + mCommonResult.getReturnMsg(), Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            Toast.makeText(NewAddressActivity.this, "" + mCommonResult.getReturnMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(CommonResult commonResult) {
                        mCommonResult = commonResult;
                    }
                }));
    }

    /**
     * 获取会员收货地址
     *
     * @param companyid 站点ID
     * @param code      安全校验码
     * @param timestamp 时间戳
     * @param pagesize  每页显示数量
     * @param pageindex 当前页数
     * @param addressid 收货地址ID
     * @param main      为1时加载默认收货地址，其它调用所有
     * @return
     */
    public void getAdressList(String companyid, String code, String timestamp, int pagesize, int pageindex, int main, String addressid) {

        mCompositeSubscription.add(manager.getAddressList(companyid, code, timestamp, pagesize, pageindex, main, addressid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Address>() {
                    @Override
                    public void onCompleted() {
                        Log.e(TAG, "onCompleted: " + mAddress.toString());
                        int status = mAddress.getStatus();
                        if (status > 0) {
                            etName.setText(mAddress.getDelivery_AddressList().get(0).getAddressName());
                            etPhone.setText(mAddress.getDelivery_AddressList().get(0).getAddressPhone());
                            tvDiqu.setText(mAddress.getDelivery_AddressList().get(0).getAddressProvince() + mAddress.getDelivery_AddressList().get(0).getAddressCity() + mAddress.getDelivery_AddressList().get(0).getAddressArea());
                            mProvince = mAddress.getDelivery_AddressList().get(0).getAddressProvince();
                            mCity = mAddress.getDelivery_AddressList().get(0).getAddressCity();
                            mArea = mAddress.getDelivery_AddressList().get(0).getAddressArea();
                            etAddressdetail.setText(mAddress.getDelivery_AddressList().get(0).getAddressXX());
                            etPostalcode.setText(mAddress.getDelivery_AddressList().get(0).getAddressZipcode() + "");
                            cbDefault.setChecked(mAddress.getDelivery_AddressList().get(0).isAddressDefault());
                        } else {
                            Toast.makeText(NewAddressActivity.this, "" + mAddress.getReturnMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError: " + e.toString());
                    }

                    @Override
                    public void onNext(Address address) {
                        mAddress = address;
                    }
                }));
    }
}

